#!/bin/sh

# build script for vkd3d-proton

# Copyright 2022 orbea
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

set -euf

cd -- "$(cd -- "${0%/*}/" && pwd -P)"

PRGNAM=vkd3d-proton
SRCNAM=$(printf %s\\n "$PRGNAM" | tr - _)
BRANCH=${BRANCH:-master}
URL="https://github.com/HansKristian-Work/$PRGNAM"

. ../../functions
. ../env.tools

_git "$SRC" "$PRGNAM" "$URL" "$TMP" "$BRANCH" "${COMMIT:-}" 1
_flags meson

if _exists i686-w64-mingw32-g++ x86_64-w64-mingw32-g++ >/dev/null 2>&1; then
  arch='32 64'
elif _exists i686-w64-mingw32-g++ >/dev/null 2>&1; then
  arch=32
elif _exists x86_64-w64-mingw32-g++ >/dev/null 2>&1; then
  arch=64
else
  _die 1 'ERROR: mingw-w64 is not installed.'
fi

eval "set -- $arch"

for bin do
  CFLAGS="$BLDFLAGS" \
  CXXFLAGS="$BLDFLAGS" \
  _meson "$TMP"/build$bin \
    --libdir=share/$SRCNAM/x$bin \
    --bindir=share/$SRCNAM/x$bin \
    --cross-file=build-win$bin.txt
done

mkdir -p -- "$DST$PKG"/bin

cat > "$DST$PKG"/bin/setup_$SRCNAM<<EOF
#!/bin/sh

set -eu

install=

while [ \$# -gt 0 ]; do
  option="\$1"
  shift

  case "\$option" in
    -- )
      break
    ;;
    install|uninstall )
      install="\$option"
    ;;
    * )
      printf '%s\\n' "Unrecognized option '\$option'." >&2
      exit 1
    ;;
  esac
done

$DST$PKG/share/$SRCNAM/setup_$SRCNAM.sh "\$install" --symlink
EOF

cp setup_$SRCNAM.sh "$DST$PKG"/share/$SRCNAM/setup_$SRCNAM.sh
chmod 0755 "$DST$PKG"/share/$SRCNAM/setup_$SRCNAM.sh
chmod 0755 "$DST$PKG"/bin/setup_$SRCNAM

_install_strip "$PRGNAM" "$VERSION" "$PKG" "$SRC" LICENSE README.md

exit 0
